// 初始化问卷创建页面
document.addEventListener('DOMContentLoaded', function() {
    // 初始化拖拽排序
    const questionList = document.getElementById('questionList');
    if (questionList) {
        new Sortable(questionList, {
            animation: 150,
            handle: '.drag-handle',
            ghostClass: 'sortable-ghost',
            chosenClass: 'sortable-chosen',
            dragClass: 'sortable-drag',
            onEnd: function(evt) {
                updateQuestionOrder();
            }
        });
    }
});

// 添加问题
function addQuestion(type) {
    const questionList = document.getElementById('questionList');
    const questionCount = questionList.children.length;
    const questionDiv = document.createElement('div');
    questionDiv.className = 'card mb-3';
    questionDiv.innerHTML = getQuestionTemplate(type, questionCount);
    questionList.appendChild(questionDiv);
    updateQuestionNumbers();
}

// 获取问题模板
function getQuestionTemplate(type, index) {
    const questionTypes = {
        0: '单选题',
        1: '多选题',
        2: '填空题',
        3: '评分题'
    };
    
    let template = `
        <div class="card-body">
            <div class="d-flex justify-content-between mb-3">
                <div class="d-flex align-items-center">
                    <button type="button" class="btn btn-outline-secondary btn-sm me-2 drag-handle" style="cursor: move;">
                        <i class="fas fa-grip-vertical"></i>
                    </button>
                    <h5 class="card-title mb-0">${questionTypes[type]}</h5>
                </div>
                <div class="btn-group">
                    <button type="button" class="btn btn-outline-danger btn-sm" onclick="deleteQuestion(this)">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
            <div class="mb-3">
                <input type="text" class="form-control" name="Questions[${index}].QuestionText" placeholder="请输入问题" required>
                <input type="hidden" name="Questions[${index}].Type" value="${type}">
                <input type="hidden" name="Questions[${index}].Order" value="${index + 1}">
                <input type="hidden" name="Questions[${index}].IsRequired" value="true">
            </div>`;

    if (type === 0 || type === 1) {
        template += `
            <div class="options-container" data-question-index="${index}">
                <div class="option-item mb-2">
                    <div class="input-group">
                        <div class="input-group-text">
                            <input type="${type === 0 ? 'radio' : 'checkbox'}" disabled>
                        </div>
                        <input type="text" class="form-control" name="Questions[${index}].Options[0].OptionText" placeholder="选项1" required>
                        <input type="hidden" name="Questions[${index}].Options[0].Order" value="1">
                        <button type="button" class="btn btn-outline-danger" onclick="deleteOption(this)">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
            </div>
            <button type="button" class="btn btn-outline-primary btn-sm mt-2" onclick="addOption(this, ${type})">
                <i class="fas fa-plus"></i> 添加选项
            </button>`;
    } else if (type === 2) {
        template += `
            <div class="form-group">
                <textarea class="form-control" disabled placeholder="此处将显示文本输入框"></textarea>
            </div>`;
    } else if (type === 3) {
        template += `
            <div class="rating-preview d-flex justify-content-center gap-2">
                <i class="fas fa-star"></i>
                <i class="fas fa-star"></i>
                <i class="fas fa-star"></i>
                <i class="fas fa-star"></i>
                <i class="fas fa-star"></i>
            </div>`;
    }

    template += `</div>`;
    return template;
}

// 添加选项
function addOption(button, type) {
    const optionsContainer = button.previousElementSibling;
    const questionIndex = optionsContainer.dataset.questionIndex;
    const optionCount = optionsContainer.children.length;
    const optionDiv = document.createElement('div');
    optionDiv.className = 'option-item mb-2';
    optionDiv.innerHTML = `
        <div class="input-group">
            <div class="input-group-text">
                <input type="${type === 0 ? 'radio' : 'checkbox'}" disabled>
            </div>
            <input type="text" class="form-control" name="Questions[${questionIndex}].Options[${optionCount}].OptionText" placeholder="选项${optionCount + 1}" required>
            <input type="hidden" name="Questions[${questionIndex}].Options[${optionCount}].Order" value="${optionCount + 1}">
            <button type="button" class="btn btn-outline-danger" onclick="deleteOption(this)">
                <i class="fas fa-times"></i>
            </button>
        </div>`;
    optionsContainer.appendChild(optionDiv);
}

// 删除选项
function deleteOption(button) {
    const optionItem = button.closest('.option-item');
    const optionsContainer = optionItem.closest('.options-container');
    optionItem.remove();
    updateOptionOrder(optionsContainer);
}

// 删除问题
function deleteQuestion(button) {
    if (confirm('确定要删除这个问题吗？')) {
        button.closest('.card').remove();
        updateQuestionOrder();
    }
}

// 更新问题顺序
function updateQuestionOrder() {
    const questions = document.querySelectorAll('#questionList .card');
    questions.forEach((question, index) => {
        // 更新问题索引
        const inputs = question.querySelectorAll('input[name*="Questions["]');
        inputs.forEach(input => {
            const name = input.name;
            const newName = name.replace(/Questions\[\d+\]/, `Questions[${index}]`);
            input.name = newName;
        });
        
        // 更新问题顺序
        const orderInput = question.querySelector('input[name$="].Order"]');
        if (orderInput) {
            orderInput.value = index + 1;
        }
        
        // 更新选项容器的问题索引
        const optionsContainer = question.querySelector('.options-container');
        if (optionsContainer) {
            optionsContainer.dataset.questionIndex = index;
        }
    });
}

// 更新选项顺序
function updateOptionOrder(container) {
    const options = container.querySelectorAll('.option-item');
    const questionIndex = container.dataset.questionIndex;
    options.forEach((option, index) => {
        const textInput = option.querySelector('input[type="text"]');
        const orderInput = option.querySelector('input[type="hidden"]');
        textInput.name = `Questions[${questionIndex}].Options[${index}].OptionText`;
        orderInput.name = `Questions[${questionIndex}].Options[${index}].Order`;
        orderInput.value = index + 1;
    });
}

// 预览问卷
function previewSurvey() {
    const previewContent = document.getElementById('previewContent');
    const form = document.getElementById('surveyForm');
    const formData = new FormData(form);
    
    let preview = `
        <h3>${formData.get('Title') || '问卷标题'}</h3>
        <p class="text-muted">${formData.get('Description') || '问卷说明'}</p>
        <hr>`;
    
    const questions = document.querySelectorAll('#questionList .card');
    questions.forEach((question, index) => {
        const questionText = question.querySelector('input[name$="QuestionText"]').value;
        const questionType = parseInt(question.querySelector('input[name$="Type"]').value);
        
        preview += `
            <div class="mb-4">
                <h5>${index + 1}. ${questionText}</h5>`;
                
        if (questionType === 0 || questionType === 1) {
            const options = question.querySelectorAll('.option-item input[type="text"]');
            options.forEach((option, optIndex) => {
                preview += `
                    <div class="form-check">
                        <input class="form-check-input" type="${questionType === 0 ? 'radio' : 'checkbox'}" disabled>
                        <label class="form-check-label">${option.value}</label>
                    </div>`;
            });
        } else if (questionType === 2) {
            preview += `<textarea class="form-control" disabled></textarea>`;
        } else if (questionType === 3) {
            preview += `
                <div class="rating-preview d-flex justify-content-center gap-2">
                    <i class="fas fa-star"></i>
                    <i class="fas fa-star"></i>
                    <i class="fas fa-star"></i>
                    <i class="fas fa-star"></i>
                    <i class="fas fa-star"></i>
                </div>`;
        }
        
        preview += `</div>`;
    });
    
    previewContent.innerHTML = preview;
    new bootstrap.Modal(document.getElementById('previewModal')).show();
}

// 保存问卷
function saveSurvey() {
    const form = document.getElementById('surveyForm');
    const questionList = document.getElementById('questionList');
    
    // 检查是否添加了问题
    if (questionList.children.length === 0) {
        alert('未添加题目，请检查后重新发布');
        return;
    }
    
    if (form.checkValidity()) {
        if (confirm('确定要保存问卷吗？')) {
            form.submit();
        }
    } else {
        form.reportValidity();
    }
}

function validateQuestion(question) {
    if (question.isRequired) {
        const questionElement = document.querySelector(`[data-question-id="${question.id}"]`);
        const selectedOptions = questionElement.querySelectorAll('input[type="checkbox"]:checked');
        
        if (selectedOptions.length === 0) {
            alert(`问题 "${question.questionText}" 至少需要选择一个选项`);
            return false;
        }
    }
    return true;
} 